package guowenlong.golf.ui.personal.info;

import static me.wenlong.mixutils.MixUtils.mContext;

import android.Manifest.permission;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.baoyz.actionsheet.ActionSheet;
import com.baoyz.actionsheet.ActionSheet.ActionSheetListener;
import guowenlong.golf.R;
import guowenlong.golf.widget.SquareImageView;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import me.wenlong.mixutils.util.LogUtils;

/**
 * des   : 描述
 * author: Administrator
 * email : guowenlong20000@gmail.com
 * time  : 2017年03月25日 下午 2:56.
 */

public class ChangeHeadImageActivity extends AppCompatActivity implements
    ActionSheetListener {

  @BindView(R.id.btn_changeheadimage)
  Button btnChangeheadimage;
  @BindView(R.id.btn_saveheadimage)
  Button btnSaveheadimage;
  @BindView(R.id.btn_cancel)
  Button btnCancel;
  @BindView(R.id.siv_head)
  SquareImageView sivHead;

  private String picPath;
  public static final int PHOTO = 0;
  public static final int CAMERA = 1;
  private Uri imageUri;
  public String path;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    restoreActionBar();
    setContentView(R.layout.activity_change_head_image);
    ButterKnife.bind(this);
    setTheme(R.style.ActionSheetStyleiOS7);

    picPath = getCacheDir() + "/" + "temp.png";

  }

  public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.hide();
    actionBar.setDisplayShowTitleEnabled(false);
  }

  private void showDialog() {
    ActionSheet.createBuilder(this, getSupportFragmentManager())
        .setCancelButtonTitle("取消")
        .setOtherButtonTitles("从相册选择", "拍一张")
        .setCancelableOnTouchOutside(true)
        .setListener(this).show();
  }

  @Override
  public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

  }

  @Override
  public void onOtherButtonClick(ActionSheet actionSheet, int index) {
    switch (index) {
      case 1:// 拍照
        actionSheet.dismiss();
        if (ContextCompat.checkSelfPermission(this,
            permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
          ActivityCompat.requestPermissions(this,
              new String[]{permission.CAMERA}, 1);
        } else {
          imageFromCamara();
        }
        break;
      case 0:// 从相册中选取
        actionSheet.dismiss();
        if (ContextCompat.checkSelfPermission(this,
            permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
          ActivityCompat
              .requestPermissions(
                  this,
                  new String[]{permission.READ_EXTERNAL_STORAGE},
                  2);
        } else {
          imageFromPhoto();
        }
        break;
    }
  }

  public void imageFromCamara() {
    /**
     * 最后一个参数是文件夹的名称，可以随便起
     */
    File file = new File(Environment.getExternalStorageDirectory(), "拍照");
    if (!file.exists()) {
      file.mkdir();
    }
    /**
     * 这里将时间作为不同照片的名称
     */
    File output = new File(file, System.currentTimeMillis() + ".jpg");

    /**
     * 如果该文件夹已经存在，则删除它，否则创建一个
     */
    try {
      if (output.exists()) {
        output.delete();
      }
      output.createNewFile();
    } catch (Exception e) {
      e.printStackTrace();
    }
    /**
     * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
     * 将文件转化为uri
     */
    imageUri = Uri.fromFile(output);
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, CAMERA);
  }

  public void imageFromPhoto() {
    Intent i = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, PHOTO);
  }

  @OnClick({R.id.btn_changeheadimage, R.id.btn_saveheadimage, R.id.btn_cancel})
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.btn_changeheadimage:
        showDialog();
        break;
      case R.id.btn_saveheadimage:
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        finish();
        break;
      case R.id.btn_cancel:
        finish();
        break;
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    LogUtils.e("test" + requestCode + "   " + resultCode + "   " + data.toString());
    if (resultCode == RESULT_OK && data.getData() != null) {
      switch (requestCode) {
        case CAMERA:
          Bitmap bit = null;
          try {
            bit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }
          sivHead.setImageBitmap(bit);
          break;
        case PHOTO:
          Bitmap bitmap = BitmapFactory.decodeFile(getBitmap(data));
          sivHead.setImageBitmap(bitmap);
          break;
      }
      super.onActivityResult(requestCode, resultCode, data);
    } else {
      LogUtils.e(requestCode + "   " + resultCode + "   " + data.toString());
    }
  }

  private String getBitmap(Intent data) {
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver()
        .query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String url = cursor.getString(columnIndex);
    cursor.close();
    return url;
  }

  public static boolean saveImage(Bitmap photo, String spath) {
    try {
      BufferedOutputStream bos = new BufferedOutputStream(
          new FileOutputStream(spath, false));
      photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
      bos.flush();
      bos.close();
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }


  @Override
  public void onRequestPermissionsResult(int requestCode,
      String[] permissions, int[] grantResults) {
    if (requestCode == PHOTO) {
      if (grantResults.length > 0
          && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        imageFromPhoto();
      } else {
        Toast.makeText(mContext, "如果不给与权限部分功能将影响您的使用", Toast.LENGTH_SHORT).show();
      }
    } else if (requestCode == CAMERA) {
      if (grantResults.length > 0
          && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        imageFromCamara();
      } else {
        Toast.makeText(mContext, "如果不给与权限部分功能将影响您的使用", Toast.LENGTH_SHORT).show();
      }
    }
  }
}